import datetime

from querier.esquerier import ElasticSearchQuerier
# import utils
# import math


class WeiboTrendInfluenceQuerier(ElasticSearchQuerier):
    def __init__(self, es, index, doc_type):
        super(WeiboTrendInfluenceQuerier, self).__init__(es, index, doc_type)
        # self.nlp_service = nlp_service

    def _build_query(self, args):
        user_id = args.get('user_id', None)
        from_date = args.get('from', None)
        to_date = args.get('to', None)
        if user_id is None:
            raise ValueError('"user_id" is needed.')

        query = self._genQuery(user_id, from_date, to_date)
        return query, {}, {'user_id': user_id, 'from': from_date, 'to': to_date}

    def _build_result(self, es_result, param):
        # total = es_result['hits']['total']
        hits = es_result['hits']['hits']
        data = extractResult(hits)
        return {
            'user_id': param['user_id'],
            'from': param['from'],
            'to': param['to'],
            'dates': data['dates'],
            'score': data['score'],
            'fans': data['fans'],

        }

    def _genQuery(self, user_id, from_date, to_date):
        query = {
            "query": {
                "bool": {
                    "filter": [
                        {'term': {'user_id': user_id}},
                        {
                            "range": {
                                        "date": {
                                            "from": from_date,
                                            "to": to_date
                                        }
                                    }
                        }
                    ]
                }
            },
            "sort": {"date": "asc"},
            "size": 10000
        }

        return query


def extractResult(hits):
    dates = []
    influences = []
    fans = []
    for h in hits:
        source_ = h['_source']
        dates.append(str(datetime.datetime.strptime(source_['date'], '%Y%m%d'))[0:10])
        influences.append(source_['score'])
        fans.append(source_['fans'])

    return {
        'score': influences,
        'dates': dates,
        'fans': fans
    }


